package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.entity.Teacher;
import com.example.educationalsystem.entity.User;
import com.example.educationalsystem.entity.Vetting;
import com.example.educationalsystem.service.IVettingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static ch.qos.logback.core.joran.action.ActionConst.NULL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-26
 */
@RestController
@Api(value = "/vetting",tags = "审批信息管理")
@RequestMapping("/vetting")
public class VettingController {


    @Autowired
    private IVettingService iVettingService;

    @GetMapping("/getAllVetting")
    @ApiOperation(value = "获取所有审批信息",notes = "获取所有审批信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getAllVetting()
    {
        ResponseJson responseJson=new ResponseJson();
        List<Vetting> vettinglist=iVettingService.getBaseMapper().selectList(Wrappers.lambdaQuery());
        if(vettinglist!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(vettinglist);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，无得票信息！");
        }
        return responseJson;
    }
    @ApiOperation(value = "分页查询审批信息", notes = "分页查询审批信息，需要提供页数和一页大小（即一页几条数据）")
    @GetMapping(value = "/vettingPage")
    @ResponseBody
    public ResponseJson vettingpage(@RequestParam long current, @RequestParam long size, String approver) {
        ResponseJson responseJson = new ResponseJson();
        Page<Vetting> VettingPage = new Page<>(current, size);
        QueryWrapper<Vetting> queryWrapper=new QueryWrapper<>();
        if(approver==null)
        {
            queryWrapper=null;
        }
        if(approver!=null)
        {
            queryWrapper.eq("approver",approver);
        }
        Page<Vetting> VettingPages = iVettingService.getBaseMapper().selectPage(VettingPage, queryWrapper);
        responseJson.setMsg("分页查询成功");
        responseJson.setData(VettingPages);
        responseJson.setStatus(200);
        return responseJson;
    }
    @ApiOperation(value = "增加审批信息",notes = "增加一条审批信息记录")
    @PostMapping("/insertVetting")
    @ResponseBody
    public ResponseJson insertVetting(@RequestBody Vetting requestVetting)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Vetting> queryWrapper=new QueryWrapper<>();
        Boolean result=iVettingService.save(requestVetting);
        if(result)
        {
            responseJson.setMsg("增加成功！");
            responseJson.setStatus(200);
            responseJson.setData(requestVetting);

        }
        else
        {
            responseJson.setStatus(400);
            responseJson.setMsg("增加失败！");
        }

        return responseJson;
    }

    @ApiOperation(value = "批量删除审批信息",notes = "根据审批编号，删除多条审批信息")
    @DeleteMapping("/deleteVettings")
    @ResponseBody
    public  ResponseJson deleteVettings( @ApiParam(name = "Ids", value = "审批IDs", required = true) @RequestParam String Ids)
    {
        ResponseJson responseJson=new ResponseJson();
        String[] idArr = Ids.split(",");
        List<String> idList = Arrays.asList(idArr);
        boolean result=iVettingService.removeByIds(idList);
        System.out.println(result);
        if(result)
        {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }
    @ApiOperation(value = "删除审批信息",notes = "根据ID，删除一条审批信息")
    @DeleteMapping("/deleteVetting")
    @ResponseBody
    public  ResponseJson deleteVetting( @ApiParam(name = "Id", value = "审批ID", required = true) @RequestParam String Id)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Vetting> queryWrapper=new QueryWrapper<>();
        Vetting vettingOne=iVettingService.getBaseMapper().selectOne(queryWrapper.eq("id",Id));
        if(vettingOne!=null)
        {
            int result=iVettingService.getBaseMapper().deleteById(vettingOne.getId());
            System.out.println(result);
            if(result==1)
            {
                responseJson.setData(vettingOne);
                responseJson.setMsg("删除成功！");
                responseJson.setStatus(200);
            }
            else
            {
                responseJson.setMsg("删除失败");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("该审批信息不存在！");
        }
        return responseJson;

    }
    @ApiOperation(value = "导出所有审批信息",notes = "导出所有审批信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response, @RequestParam String tableName) throws IOException {

        try{
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename="+ new String(tableName.getBytes(StandardCharsets.UTF_8),"ISO8859-1")+".xls");
            EasyExcel.write(response.getOutputStream(), Vetting.class).sheet(tableName).doWrite(iVettingService.getBaseMapper().selectList(Wrappers.lambdaQuery()));
        }catch(Exception e)
        {
            response.reset();
        }


    }
    @ApiOperation(value = "导入审批信息",notes = "导入审批信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson myImport(MultipartFile file) {
        ResponseJson responseJson=new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, Vetting.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            if (list.size() >= 1) {
                for (int i = 0; i < list.size(); i++) {
                    Vetting vetting= (Vetting) list.get(i);
                    //使用mybatis-plus添加到数据库
                    iVettingService.save(vetting);
                }
            }
            responseJson.setStatus(200);
            responseJson.setMsg("导入成功！");
        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg("导入失败！");
            e.printStackTrace();
        }

        return responseJson;
    }
    @ApiOperation(value = "更新审批信息",notes = "更新审批信息，必须填写ID")
    @PutMapping("/updateVetting")
    @ResponseBody
    public ResponseJson updateVetting(@RequestBody  Vetting resquestVetting)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Vetting> queryWrapper=new QueryWrapper<>();
        Vetting vettingOne=iVettingService.getBaseMapper().selectOne(queryWrapper.eq("id",resquestVetting.getId()));
        if(vettingOne!=null)
        {
            QueryWrapper<Vetting> queryWrapper1=new QueryWrapper<>();
            int result=iVettingService.getBaseMapper().update(resquestVetting,queryWrapper1.eq("id",resquestVetting.getId()));
            if(result==1)
            {
                responseJson.setMsg("更新成功！");
                responseJson.setStatus(200);
                responseJson.setData(resquestVetting);
            }
            else {
                responseJson.setMsg("更新失败！");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setMsg("该审批信息不存在");
            responseJson.setStatus(404);
        }
        return responseJson;
    }
}

